package handel

import (
	"car-order/cache"
	"car-order/model"
	"car-order/pkg"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	redis_key := "user_login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次以上禁止登录",
		})
		return
	}
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	var user model.User
	err := model.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次封禁两个小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}
func RoleNode(c *gin.Context) {
	role_id, _ := strconv.Atoi(c.PostForm("role_id"))
	node_id, _ := strconv.Atoi(c.PostForm("node_id"))
	data := model.RoleNode{
		RoleID: role_id,
		NodeId: node_id,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func UserNodeList(c *gin.Context) {
	/*
			SELECT
		  *
		FROM
		  roles
		  LEFT JOIN user_roles ON user_roles.role_id = roles.id
		  WHERE user_roles.user_id=1
	*/
	id := c.Query("id")
	var role model.Role
	model.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON user_roles.role_id = roles.id").
		Where("user_roles.user_id=?", id).
		Find(&role)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": role,
	})

}
func NodeRoleList(c *gin.Context) {
	/*
			SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN role_nodes ON role_nodes.node_id = nodes.id
	*/
	id := c.Query("id")
	var node model.Node
	model.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON role_nodes.node_id = nodes.id").
		Where("role_nodes.role_id=?", id).
		Find(&node)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": node,
	})
}
